/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.browser;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.util.*;
import com.blandware.atleap.model.core.ContentResource;
import com.blandware.atleap.service.core.ContentResourceManager;
import com.blandware.atleap.webapp.taglib.core.grid.util.FilterConditions;
import com.blandware.atleap.webapp.taglib.core.grid.util.Grid;
import com.blandware.atleap.webapp.taglib.core.grid.util.StringFilter;
import com.blandware.atleap.webapp.util.core.VirtualFolder;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.oro.text.regex.*;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.commons.validator.GenericValidator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * <p>Gets collection of files and folders to display in browser
 * </p>
 * <p><a href="CallCreateActionPageAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.25 $ $Date: 2007/12/19 12:49:51 $
 * @struts.action path="/core/browser/browseFiles"
 * validate="false"
 * roles="core-browser-file"
 * @struts.action-forward name="showBrowser"
 * path=".core.browser.fileBrowser"
 */
public final class BrowseFilesAction extends BaseBrowserAction {

	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        HttpSession session = request.getSession();

        boolean opening = getOpening(request);
        String modeToRequest = WebappConstants.BROWSER_MODE_FILES;
        if (!GenericValidator.isBlankOrNull(request.getParameter("mode"))) {
            modeToRequest = request.getParameter("mode");
        }
        String mode = processOpeningAndGetMode(opening, session,
                                               modeToRequest, WebappConstants.BROWSER_MODE_LINKS);

        // computing name of menu
        computeMenuNameAndSaveToRequest(mode, request);

		String currentFolder = "";
        if ( request.getParameter("currentFolder") != null ) {
			currentFolder = request.getParameter("currentFolder");
			session.setAttribute(WebappConstants.CONTENT_RESOURCES_CURRENT_PATH_KEY, currentFolder);
		} else if ( session.getAttribute(WebappConstants.CONTENT_RESOURCES_CURRENT_PATH_KEY) != null ) {
			currentFolder = (String) session.getAttribute(WebappConstants.CONTENT_RESOURCES_CURRENT_PATH_KEY);
		}

		if ( currentFolder == null || currentFolder.equals("/") ) {
			currentFolder = "";
		}

		// ensure, that current folder starts with slash and does not end with slash
		if ( currentFolder.length() > 0 ) {
			if ( !currentFolder.startsWith("/") ) {
				currentFolder = "/" + currentFolder;
			}
			if ( currentFolder.endsWith("/") ) {
				currentFolder = currentFolder.substring(0, currentFolder.length() - 1);
			}
		}

		// get all content resources, which exist in surrent folder

		StringFilter uriFilter = new StringFilter("r.uri");
		uriFilter.createFirstClause(FilterConditions.STRING_STARTS_WITH, Constants.RESOURCES_URI_PREFIX + currentFolder + "/");

		Grid crGrid = getGridByName(WebappConstants.BROWSE_FILES_GRID, session);
		if ( crGrid == null ) {
			crGrid = new Grid(WebappConstants.BROWSE_FILES_GRID);
		}

		crGrid.addFilter(uriFilter);

		saveGrid(crGrid, session);

		QueryInfo queryInfo = new QueryInfo();
		queryInfo.setWhereClause(crGrid.getWhereClause());

		Map queryParameters = new HashMap();
		queryParameters.put("contentResourceType", Constants.RESOURCE_TYPE_FILE);
		queryInfo.setQueryParameters(queryParameters);

		ContentResourceManager contentResourceManager = (ContentResourceManager) getBean(Constants.CONTENT_RESOURCE_MANAGER_BEAN);
		PartialCollection contentResources = contentResourceManager.listContentResources(queryInfo);

		// we have list of action resources which are all placed in current folder
		// we only need to divide acquired set to subfolders and resources
		// we need regular expression in order to do it:
		String folderPatternString = "(" + RegExUtil.escapeMetasymbols(Constants.RESOURCES_URI_PREFIX + currentFolder) + ")";
		folderPatternString += "\\/([^\\/]+)(\\/[^\\/]+)+";

		// pattern compiler instance to use
		PatternCompiler compiler = new Perl5Compiler();

		// compiled patterns
		Pattern folderPattern = compiler.compile(folderPatternString);

		// pattern matcher instance to use
		PatternMatcher matcher = new Perl5Matcher();

		// list of folders
		SortedSet folderSet = new TreeSet();

		// list of resources
		List files = new ArrayList();

		for ( Iterator i = contentResources.iterator(); i.hasNext(); ) {
			ContentResource contentResource = (ContentResource) i.next();
			String uri = contentResource.getUri();

			// check folder name
			if ( matcher.matches(uri, folderPattern) ) {
				MatchResult result = matcher.getMatch();

				// according to pattern, folder name is in second group
				Folder folder = new VirtualFolder(result.group(2), currentFolder, '/');
				folderSet.add(folder);

			} else {
				// add resource to list
				ContentResource tmp = new ContentResource();
				WebappUtil.copyProperties(tmp, contentResource, request);
				int prefixLength = Constants.RESOURCES_URI_PREFIX.length();
				uri = uri.substring(prefixLength);
				tmp.setUri(uri.substring(currentFolder.length() + 1));
				files.add(tmp);
			}
		}

		// create parent folder if current folder is not the root folder
		Folder parentFolder = null;
		if ( currentFolder.length() > 0 ) {
			int k = currentFolder.lastIndexOf("/");
			if ( k < 0 ) {
				k = 0;
			}
			String parentFolderPath = currentFolder.substring(0, k);
			parentFolder = new VirtualFolder("..", parentFolderPath, '/', true);
		}

		LinkedList folders = new LinkedList(folderSet);
		if ( parentFolder != null ) {
			folders.addFirst(parentFolder);
		}

		request.setAttribute(WebappConstants.BROWSER_FILES_COLLECTION_KEY, files);
		request.setAttribute(WebappConstants.FOLDERS_COLLECTION_KEY, folders);

		request.setAttribute(WebappConstants.CURRENT_PATH_KEY, new FolderList(VirtualFolder.splitPath(currentFolder)));

        if (opening) {
            String inputId = request.getParameter("inputId");
            if ( inputId != null && inputId.length() != 0 ) {
                session.setAttribute(WebappConstants.HTML_INPUT_TAG_ID_KEY, inputId);
            } else {
                session.removeAttribute(WebappConstants.HTML_INPUT_TAG_ID_KEY);
            }
        }

        return mapping.findForward("showBrowser");
	}

}